/**
 * 
 */
package me.joshua.tools4j.service.task;

import java.util.LinkedList;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import me.joshua.tools4j.dal.SubscriptionRepository;
import me.joshua.tools4j.model.Subscription;
import me.joshua.tools4j.service.MailService;
import me.joshua.tools4j.service.SubscriptionService;

import org.apache.commons.lang3.time.DatePrinter;
import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

/**
 * @author <a href="mailto:daonan.zhan@gmail.com">Joshua Zhan</a>
 * 
 */
@Service
public class SubscriptionTask {

	private static final Logger			LOGGER			= LoggerFactory.getLogger(SubscriptionTask.class);
	private static final DatePrinter	DATE_PRINTER	= FastDateFormat.getInstance("yyyyMMdd");

	@Autowired
	private MailService					mailService;
	@Autowired
	private SubscriptionRepository		subscriptionRepository;
	@Autowired
	private SubscriptionService			subscriptionService;
	@Autowired
	@Qualifier("mailTemplateEngine")
	private TemplateEngine				templateEngine;

	@Scheduled(cron = "0 0 19 * * ?")
	public void checkAll() {
		List<Subscription> tasks = subscriptionRepository.findByEnabled(true);
		List<Subscription> updatedList = new LinkedList<Subscription>();
		List<Subscription> unchangedList = new LinkedList<Subscription>();
		for (Subscription task : tasks) {
			if (subscriptionService.check(task)) {
				updatedList.add(task);
			} else {
				unchangedList.add(task);
			}
		}

		String date = DATE_PRINTER.format(System.currentTimeMillis());

		Context context = new Context();
		context.setVariable("date", date);
		context.setVariable("tasks", tasks);
		context.setVariable("updatedList", updatedList);
		context.setVariable("unchangedList", unchangedList);
		String mailContent = templateEngine.process("/pageNotification", context);

		MimeMessage message = mailService.createMimeMessage();
		MimeMessageHelper messageHelper = new MimeMessageHelper(message, "UTF-8");
		MimeMailMessage mailMessage = new MimeMailMessage(messageHelper);
		mailMessage.setTo("daonan.zhan@gmail.com");
		mailMessage.setSubject("[" + date + "]Tools4J页面订阅通知");
		mailMessage.setFrom("testforjoshua@gmail.com");

		try {
			mailMessage.getMimeMessageHelper().setText(mailContent, true);
		} catch (MessagingException e) {
			LOGGER.error("Mail creation error", e);
		}
		mailService.send(mailMessage);
	}
}
